<template>
  <div class="cesium-draw">
    <div id="cesium-drawer" />
    <div class="mouse-postion">{{ nowPostion.wgs84 }}</div>
    <div class="tool-box">
      <!-- <div class="slider-box-wrapper"><slider-box v-model:value="terrainExaggeration" :max="2" /></div> -->
      <!-- <div class="slider-box-wrapper"><slider-box v-model:value="relativeHeight" :max="10000" /></div> -->
      <!-- <div class="select-box-wrapper"><select-box :options="locationToolbarOptions" /></div>
      <div class="select-box-wrapper"><select-box :options="sizeOptions" /></div>
      <div class="select-box-wrapper"><a-checkbox v-model:checked="shadows">shadows</a-checkbox></div>
      <div class="select-box-wrapper"><a-checkbox v-model:checked="terrainShadows">terrain shadows</a-checkbox></div> -->
      <div class="select-box-wrapper"><a-checkbox v-model:checked="picking">选择</a-checkbox></div>
      <div class="select-box-wrapper"><select-box :options="layerOptions" /></div>
      <div id="menu">
        <!-- <p><button @click="onClick('play')">播放</button></p> -->
        <!-- <p><button @click="onClick('stop')">暂停</button></p> -->
      </div>
    </div>
  </div>
</template>

<script>
//参考：https://sandcastle.cesium.com/?src=3D%20Tiles%20BIM.html
import { DownOutlined, EditOutlined } from '@ant-design/icons-vue';
import { defineComponent, ref, watch } from 'vue';
import SliderBox from '@components/widgets/slider-box';
import SelectBox from '@components/widgets/select-box';
import * as Cesium from '@cesium/Source/Cesium.js';
import MousePosition from '@functional/utils/mousePosition';

export default defineComponent({
  name: 'powerplant', // 电厂
  components: { DownOutlined, EditOutlined, SliderBox, SelectBox },
  setup() {
    return {
      viewer: null,
      doPicking: () => {}
    };
  },
  data() {
    return {
      nowPostion: {},
      layerOptions: [],
      selectedFeature: null,
      picking: true,
    };
  },
  computed: {},
  watch: {
    picking(val) {
      this.viewer && (this.doPicking(val));
    },
  },
  mounted() {
    this.initViewer();
  },
  beforeUnmount() {
    if (this.viewer) {
      this.viewer.destroy();
      this.viewer = null;
    }
  },
  methods: {
    addPowerPlant(){
      let vm = this;
      const viewer = this.viewer;
      var scene = viewer.scene;

      var powerplant = scene.primitives.add(
        new Cesium.Cesium3DTileset({
          url: Cesium.IonResource.fromAssetId(8564),
          colorBlendMode: Cesium.Cesium3DTileColorBlendMode.REPLACE,
          // show: false
        })
      );
      powerplant.colorBlendMode = Cesium.Cesium3DTileColorBlendMode.REPLACE;
      powerplant.readyPromise
        .then(function(tileset) {
            scene.camera.setView({
              destination: new Cesium.Cartesian3(1234151.4883992162, -5086036.79436967, 3633328.4278331124),
              orientation: {
                heading: 5.593695742186853,
                pitch: -1.0786797635545216,
                roll: 6.27892466154778
              }
            });
          // viewer.zoomTo(tileset, new Cesium.HeadingPitchRange(0.5, -0.2, tileset.boundingSphere.radius * 4.0));
        })
        .otherwise(function(error) {
          console.log(error);
        });

      var pipes = viewer.entities.add({
        polyline: {
          positions: Cesium.Cartesian3.fromDegreesArray([-76.36053390920833, 34.949935893493596, -76.36055481641581, 34.94993589886988, -76.36055477047704, 34.94992280693651]),
          width: 6,
          material: new Cesium.PolylineDashMaterialProperty({
            color: Cesium.Color.YELLOW,
            dashLength: 20.0
          }),
          // show: false,
          clampToGround: true,
          classificationType: Cesium.ClassificationType.CESIUM_3D_TILE
        }
      });

      var selectedFeature;
      var picking = vm.picking;

      vm.doPicking= function(val){
        picking = val;
        vm.picking = val;
        if (!picking) {
          unselectFeature(selectedFeature);
        }
      }

      function selectFeature(feature) {
        var element = feature.getProperty('element');
        setElementColor(element, Cesium.Color.YELLOW);
        selectedFeature = feature;
        vm.selectedFeature = selectedFeature
      }

      function unselectFeature(feature) {
        if (!Cesium.defined(feature)) {
          return;
        }
        var element = feature.getProperty('element');
        setElementColor(element, Cesium.Color.WHITE);
        if (feature === selectedFeature) {
          selectedFeature = undefined;
          vm.selectedFeature = selectedFeature
        }
      }

      var handler = new Cesium.ScreenSpaceEventHandler(scene.canvas);
      handler.setInputAction(function(movement) {
        if (!picking) {
          return;
        }

        var feature = scene.pick(movement.endPosition);

        unselectFeature(selectedFeature);

        if (feature instanceof Cesium.Cesium3DTileFeature) {
          selectFeature(feature);
        }
      }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);

      // In this tileset every feature has an "element" property which is a global ID.
      // This property is used to associate features across different tiles and LODs.
      // Workaround until 3D Tiles has the concept of global batch ids: https://github.com/CesiumGS/3d-tiles/issues/265
      var elementMap = {}; // Build a map of elements to features.
      var hiddenElements = [
        112001,
        113180,
        131136,
        113167,
        71309,
        109652,
        111178,
        113156,
        113170,
        124846,
        114076,
        131122,
        113179,
        114325,
        131134,
        113164,
        113153,
        113179,
        109656,
        114095,
        114093,
        39225,
        39267,
        113149,
        113071,
        112003,
        39229,
        113160,
        39227,
        39234,
        113985,
        39230,
        112004,
        39223
      ];

      function getElement(feature) {
        return parseInt(feature.getProperty('element'), 10);
      }

      function setElementColor(element, color) {
        var featuresToColor = elementMap[element];
        var length = featuresToColor.length;
        for (var i = 0; i < length; ++i) {
          var feature = featuresToColor[i];
          feature.color = Cesium.Color.clone(color, feature.color);
        }
      }

      function unloadFeature(feature) {
        unselectFeature(feature);
        var element = getElement(feature);
        var features = elementMap[element];
        var index = features.indexOf(feature);
        if (index > -1) {
          features.splice(index, 1);
        }
      }

      function loadFeature(feature) {
        var element = getElement(feature);
        var features = elementMap[element];
        if (!Cesium.defined(features)) {
          features = [];
          elementMap[element] = features;
        }
        features.push(feature);

        if (hiddenElements.indexOf(element) > -1) {
          feature.show = false;
        }
      }

      function processContentFeatures(content, callback) {
        var featuresLength = content.featuresLength;
        for (var i = 0; i < featuresLength; ++i) {
          var feature = content.getFeature(i);
          callback(feature);
        }
      }

      function processTileFeatures(tile, callback) {
        var content = tile.content;
        var innerContents = content.innerContents;
        if (Cesium.defined(innerContents)) {
          var length = innerContents.length;
          for (var i = 0; i < length; ++i) {
            processContentFeatures(innerContents[i], callback);
          }
        } else {
          processContentFeatures(content, callback);
        }
      }

      powerplant.tileLoad.addEventListener(function(tile) {
        processTileFeatures(tile, loadFeature);
      });

      powerplant.tileUnload.addEventListener(function(tile) {
        processTileFeatures(tile, unloadFeature);
      });

      return {powerplant,pipes}
    },
    addBuilding(){
      const viewer = this.viewer;
      var scene = viewer.scene;

      var building = viewer.scene.primitives.add(
        new Cesium.Cesium3DTileset({
          url: Cesium.IonResource.fromAssetId(40866)
        })
      );
      var route = viewer.entities.add({
        polyline: {
          positions: Cesium.Cartesian3.fromDegreesArray([
            -75.59604807301078,
            40.03948512841901,
            -75.59644577413066,
            40.039316280505446,
            -75.59584544997564,
            40.03846271524258,
            -75.59661425371488,
            40.03814087821916,
            -75.59664726332451,
            40.03818297772907
          ]),
          width: 6,
          material: new Cesium.PolylineDashMaterialProperty({
            color: Cesium.Color.YELLOW
          }),
          show: false,
          clampToGround: true,
          classificationType: Cesium.ClassificationType.CESIUM_3D_TILE
        }
      });
      return {building,route}
    },
    initEffects() {
      let vm = this;
      const viewer = this.viewer;
      var scene = viewer.scene;
      var globe = scene.globe;

      const {powerplant,pipes} = this.addPowerPlant();
      const {building,route} = this.addBuilding();

      this.layerOptions = ([
        {
          text: '电厂',
          onselect: function() {
            building.show = false;
            route.polyline.show = false;
            powerplant.show = true;
            pipes.polyline.show = true;
            scene.camera.setView({
              destination: new Cesium.Cartesian3(1234151.4883992162, -5086036.79436967, 3633328.4278331124),
              orientation: {
                heading: 5.593695742186853,
                pitch: -1.0786797635545216,
                roll: 6.27892466154778
              }
            });
          }
        },
        {
          text: '建筑物',
          onselect: function() {
            building.show = true;
            route.polyline.show = true;
            powerplant.show = false;
            pipes.polyline.show = false;
            scene.camera.setView({
              destination: new Cesium.Cartesian3(1216596.5376729995, -4736445.416889214, 4081406.990364228),
              orientation: {
                heading: 5.153176564030707,
                pitch: -0.9701972964526693,
                roll: 6.277883257569513
              }
            });
          }
        }
      ]);

      this.layerOptions[0].onselect()
    },

    onViewerInited(viewer) {
      let vm = this;
      new MousePosition(viewer, pos => {
        vm.nowPostion = pos;
      });
    },

    initViewer() {
      let vm = this;
      Cesium.Ion.defaultAccessToken = $accessToken.cs;

      let osm = new Cesium.OpenStreetMapImageryProvider({
        url: 'https://a.tile.openstreetmap.org/'
      });
      let viewer = new Cesium.Viewer('cesium-drawer', {
        // imageryProvider: osm,
        // terrainProvider: Cesium.createWorldTerrain(),
        contextOptions: {
          webgl: {
            alpha: true
          }
        },
        selectionIndicator: false,
        // shadows: true,
        // terrainShadows: Cesium.ShadowMode.ENABLED,
        animation: false, //是否显示动画控件
        baseLayerPicker: false, //是否显示图层选择控件
        geocoder: false, //是否显示地名查找控件
        timeline: false, //是否显示时间线控件
        sceneModePicker: false, //是否显示投影方式控件
        navigationHelpButton: false, //是否显示帮助信息控件
        infoBox: false, //是否显示点击要素之后显示的信息
        fullscreenButton: false,
        shouldAnimate: true
      });

      // viewer.scene.globe.depthTestAgainstTerrain = true;

      this.viewer = viewer;
      this.onViewerInited(viewer);

      this.initEffects();

      // this.viewer.flyTo(this.viewer.entities);
    },
  }
});
</script>

<style lang="less">
.cesium-draw {
  position: relative;
  width: 100%;
  height: 100%;
  overflow: hidden;
  color: white;
  font-size: 14px;

  #cesium-drawer {
    width: 100%;
    height: 100%;
    overflow: hidden;
    .cesium-viewer-bottom {
      display: none !important;
    }
  }

  .mouse-postion {
    position: absolute;
    bottom: 10px;
    right: 10px;
    font-size: 14px;
    padding: 8px 12px;
    line-height: 16px;
    color: white;
    z-index: 9999;
    background-color: rgba(40, 48, 60, 1);
    border-radius: 3px;
    opacity: 0.8;
  }
}

.chart-container {
  position: absolute;
  bottom: 7px;
  left: 7px;
  background-color: rgba(0, 0, 0, 0.5);

  #profileChart {
    width: 600px;
    height: 300px;
  }
}
#canvas-a {
  top: 10px;
  display: none;
}

#canvas-b {
  top: 120px;
  display: none;
}

.tool-box {
  position: absolute;
  top: 70px;
  left: 10px;
  z-index: 9;

  #menu {
    padding-top: 20px;
    button {
      background-color: rgba(0, 0, 0, 0.75);
      border-color: rgba(0, 0, 0, 0);
      cursor: pointer;
      transition: all 500ms;
      &:hover {
        opacity: 0.75;
      }
    }
  }

  .slider-box-wrapper {
    width: 18em;
    padding: 0 10px;
    background-color: rgba(0, 0, 0, 0.75);
    margin-bottom: 10px;
  }

  .select-box-wrapper {
    padding: 5px 15px;
    background-color: rgba(0, 0, 0, 0.75);
    margin-bottom: 10px;
    width: auto;
  }
}
</style>
